<template>
  <div class="arrange-container" v-loading="Loading">
    <!-- 搜索表单 -->
    <el-form :inline="true" class="search-form">
      <el-form-item label="授权名称" class="el-form-item">
        <el-input v-model="searchForm.username" placeholder="请输入授权名称" clearable />
      </el-form-item>
    
      <el-form-item label="开始时间" class="el-form-item Time">
        <el-date-picker v-model="searchForm.startTime" type="date" placeholder="选择开始时间" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="结束时间" class="el-form-item Time">
        <el-date-picker v-model="searchForm.endTime" type="date" placeholder="选择结束时间" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="申报人数" class="el-form-item">
        <el-input v-model="searchForm.numPeople" placeholder="请输入申报人数" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" class="Button">查询</el-button>
        <el-button @click="resetForm" class="Button">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="tableData" border class="el-table" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="授权名称" width="260" />
      <el-table-column prop="specialtyName" label="报考专业" width="120" />
      <el-table-column prop="startTime" label="开始时间" width="180" />
      <el-table-column prop="endTime" label="结束时间" width="180" />

      <el-table-column prop="numPeople" label="申报人数" width="120" />
      <el-table-column prop="arrangedCount" label="已排人数" width="100" />
      <el-table-column prop="unarrangedCount" label="可排人数" width="100" />
      <el-table-column prop="scoring_method" label="考级方式" width="120" />
      <el-table-column prop="address" label="地址" width="390" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button type="primary" @click="handleManualArrange(scope.row)" :disabled="scope.row.unarrangedCount <= 0">排考</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100,200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Document, Delete } from '@element-plus/icons-vue';
  import Http from '@/utils/http';
  import { areaOptions } from '@/utils/area-data';
  import OSS from 'ali-oss';
  import { imgUrls } from '@/utils/utils';
  import { useMainStore } from '@/stores/useMain';
  const mainStore = useMainStore();

  // 搜索表单数据
  const searchForm = reactive({
   
    username: '', // 授权名称
    startTime: '',
    endTime: '',
    numPeople: '', // 申报人数
  });

  // 机构列表
  const institutions = ref([]);

  // 表格数据
  const tableData = ref([]);
  const loading = ref(false);
  const Loading = ref(false);

  // 分页数据
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);

  // 对话框相关
  const dialogVisible = ref(false);
  const currentStudent = ref(null);

  // 页面初始化
  onMounted(() => {
    fetchInstitutions();
    // fetchExamApplications()
  });
  // 获取机构列表
  const fetchInstitutions = async () => {
    try {
      const { data } = await Http.get({
        url: '/yp_admin/getSubuser',
      });
      institutions.value = data.list;
      // 如果只有一条数据，自动选中
      // if (data.list && data.list.length === 1) {
      //   searchForm.userId = data.list[0].id;
     
      // }
      handleSearch();
    } catch (error) {
      ElMessage.error('获取机构列表失败');
      console.error('获取机构列表失败:', error);
    }
  };

  // 搜索方法
  const handleSearch = () => {
    currentPage.value = 1;
    fetchExamApplications();
  };

  // 获取考级申报列表
  const fetchExamApplications = async () => {
    try {
      loading.value = true;
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        startTime: searchForm.startTime,
        endTime: searchForm.endTime,
        username: searchForm.username,
        numPeople: searchForm.numPeople,
      };
      const { data } = await Http.post({
        url: '/yp_admin/arrangingList',
        data: params,
      });
      tableData.value = data.list;
      total.value = data.total;
    } catch (error) {
      ElMessage.error('获取考级申报列表失败');
      console.error('获取考级申报列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    // 如果不是单机构，才重置 userId
    // if (institutions.value.length !== 1) {
    //   searchForm.userId = '';
    // }
    searchForm.startTime = '';
    searchForm.endTime = '';
    searchForm.numPeople = '';
    searchForm.username = '';
    handleSearch();
  };

  const handleManualArrange = (row) => {
    ElMessageBox.confirm('确认要为该考级申报进行排考吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          Loading.value = true;
          await Http.post({
            url: '/yp_admin/arrangingExam',
            data: {
              examApplicationId: row.id,
            },
          });
          ElMessage.success('排考成功');
        } catch (error) {
          ElMessage.error('排考失败');
        } finally {
          Loading.value = false;
          fetchExamApplications(); // 刷新列表
        }
      })
      .catch(() => {
        // 取消操作，不做任何处理
      });
  };

  // 分页方法
  const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchExamApplications();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchExamApplications();
  };
</script>

<style scoped lang="scss">
  //   .Time{
  //     margin-top: -8px !important;
  //     line-height: 40px !important;
  //  }
  //   :deep(.el-form-item__label) {
  //     height: 40px;
  //     line-height: 40px;
  //     padding-right: 12px;
  //     white-space: nowrap;
  //   }
  .el-form--inline .el-form-item {
    margin-right: 10px !important;
    :deep(.el-form-item__content) {
      width: 180px !important;
      .el-input {
        height: 100%;
      }
    }
  }
  .el-select,
  .el-input {
    width: 180px;
  }
  :deep(.el-input__wrapper) {
    height: 40px;
    line-height: 40px;
  }
  :deep(.el-form-item__label) {
    height: 40px;
    line-height: 40px;
  }

  .arrange-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden; // 防止溢出
    display: flex;
    flex-direction: column;

    .search-form {
      margin-bottom: 20px;
    }
  }
  .el-table {
    flex: 1;
    width: 100%;
    overflow: scroll;
  }
  .pagination-container {
    padding: 8px 20px;
    background-color: #fff;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
